package com.newx.test.open.tcp3;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Classname MCUServerWithGUI
 * @Description TODO
 * @Date 2025/1/7 16:24
 * @Created by yxl
 */
public class MCUServerWithGUI {

    public static final int BUFFER_SIZE = 1024; // 每个数据包的最大大小
    public static final int TIMEOUT_MS = 5000;  // 确认超时时间（毫秒）
    private static Socket clientSocket = null;
    private static DataOutputStream outStream = null;
    private static BufferedReader in = null;

    public static void main(String[] args) {
        String host = "127.0.0.1"; // 本地回环地址
        int port = 5000; // 监听端口

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Java服务端正在监听 " + host + ":" + port + "...");

            // 接受客户端连接
            clientSocket = serverSocket.accept();
            System.out.println("收到单片机连接请求");

            // 创建输入输出流
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            outStream = new DataOutputStream(clientSocket.getOutputStream());

            // 等待单片机发送消息
            String message = in.readLine();
            System.out.println("收到单片机消息: " + message);

            // 如果是请求文件，则启动GUI
            if (message.equals("Request file")) {
                startGUI();
            } else {
                outStream.writeUTF("Unknown command");
            }

        } catch (IOException e) {
            System.err.println("IO异常: " + e.getMessage());
        }
    }

    private static void startGUI() {
        JFrame frame = new JFrame("文件发送控制台");
        frame.setSize(300, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null);

        JButton sendButton = new JButton("发送文件");
        sendButton.setBounds(80, 40, 120, 30);
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    sendFile(outStream, in, "F:\\Desktop\\111.txt");
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                JOptionPane.showMessageDialog(frame, "文件发送完成！");
                frame.dispose(); // 关闭窗口
            }
        });

        frame.add(sendButton);
        frame.setVisible(true);
    }

    private static void sendFile(DataOutputStream outStream, BufferedReader in, String filePath) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            outStream.writeUTF("File not found: " + filePath);
            return;
        }

        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;

        // 发送文件名和文件大小
        outStream.writeUTF(file.getName());
        outStream.writeLong(file.length());

        // 发送文件内容，分包处理
        int packetNumber = 0;
        while ((bytesRead = fis.read(buffer)) != -1) {
            // 发送数据包
            outStream.writeInt(packetNumber); // 数据包序号
            outStream.writeInt(bytesRead);    // 数据长度
            outStream.write(buffer, 0, bytesRead);
            outStream.flush();

            // 等待确认
            String ack = in.readLine();
            if (ack == null || !ack.equals("ACK " + packetNumber)) {
                System.out.println("未收到确认，重传数据包 " + packetNumber);
                fis.getChannel().position(fis.getChannel().position() - bytesRead);
                continue;
            }
            System.out.println("收到确认，继续发送下一个数据包 " + packetNumber);
            packetNumber++;
        }

        fis.close();
        System.out.println("文件发送完成: " + filePath);
    }
}
